package com.cultusoft.groovin.plugins.project;

import com.cultusoft.groovin.script.Groovin;

class ProjectDirectoryFinder {

    def rootFilename = ".groovinroot"

    public String getProjectDirectory(String directoryName) {
        def rootDirectory = findRootDirectory()

        File possibleDirectory = new File(rootDirectory, directoryName) 
        if (possibleDirectory.exists()) {
            return possibleDirectory.getPath()
        }

        throw new Exception ("Unable to find project with directory $directoryName under running directory " + Groovin.RUNNING_DIRECTORY)        

    }
    
    def findCurrentProjects() {
        def projects = ProjectFactory.getProjects()
        def list = new ArrayList()
        
        File runningDir = new File (Groovin.RUNNING_DIRECTORY)
        for (project in projects) {
            if (runningDir.name.equals(project.name)) {
                list.add (project)
            }
        }
        return list
        
    }

    def findRootDirectory() {
        File runningDirectory = new File(Groovin.RUNNING_DIRECTORY)
        File currentDirectory = runningDirectory

        for (i in 0..3) {
                if (new File(currentDirectory, rootFilename).exists()) {
                    return currentDirectory
                }
                currentDirectory = currentDirectory.getParentFile()
        }

         throw new Exception ("Unable to find root directory based on $runningDirectory")
    }
}
